<template>
  <div id="container">
    <div class="header">
      <div class="form-item">
        <span>班级名:</span>
        <el-input
          placeholder="请输入班级名"
          v-model="queryParams.className"
          @keyup.enter.native="queryClass"
          clearable
        />
      </div>
      <el-button
        type="primary"
        icon="el-icon-search"
        style="margin-right: 20px"
        @click.enter="queryClass"
      >
        查询
      </el-button>

      <div class="form-item">
        <span>院系:</span>
        <el-select
          v-model="queryParams.deptId"
          placeholder="请选择院系"
          clearable
          :disabled="!departments.length"
          @change="departmentChange(queryParams.deptId)"
        >
          <el-option
            v-for="dept in departments"
            :key="dept.id"
            :label="dept.deptName"
            :value="dept.id"
          />
        </el-select>
      </div>

      <div class="form-item">
        <span>专业:</span>
        <el-select
          v-model="queryParams.majorId"
          placeholder="请选择专业"
          :disabled="!majorList.length"
          clearable
          @change="majorChange()"
        >
          <el-option
            v-for="major in majorList"
            :key="major.id"
            :label="major.majorName"
            :value="major.id"
          />
        </el-select>
      </div>

      <div class="form-item">
        <span>学期:</span>
        <el-select
          v-model="queryParams.semesterId"
          placeholder="请选择学期"
          clearable
          @change="gradeSemester"
        >
          <el-option
            v-for="semester in semesterList"
            :key="semester.id"
            :label="
              semester.term === 1
                ? `${semester.year}年第一学期`
                : `${semester.year}年第二学期`
            "
            :value="semester.id"
          />
        </el-select>
      </div>

      <div class="form-item">
        <span>分配状态:</span>
        <el-select
          v-model="queryParams.assignStatus"
          placeholder="请选择状态"
          @change="assignStatusChange"
          clearable
        >
          <el-option
            v-for="assignStatus in assignStatusList"
            :key="assignStatus.id"
            :label="assignStatus.status"
            :value="assignStatus.id"
          ></el-option>
        </el-select>
      </div>
    </div>

    <div class="content">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" label="序号" width="100" align="center" />
        <el-table-column
          prop="deptName"
          label="学院"
          width="150"
          align="center"
        />
        <el-table-column
          prop="majorName"
          label="专业"
          width="150"
          align="center"
        />
        <el-table-column
          prop="className"
          label="班级"
          width="150"
          align="center"
        />
        <el-table-column
          prop="courseName"
          label="课程名称"
          width="150"
          align="center"
        />
        <el-table-column
          prop="semesterName"
          label="学期"
          width="200"
          align="center"
        />
        <el-table-column
          :formatter="formatTeacherName"
          label="授课教师"
          width="180"
          align="center"
        />
        <el-table-column label="操作" align="center">
          <template slot-scope="{ row }">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-plus"
              @click="openAssignDialog(row)"
            >
              分配
            </el-button>

            <el-button
              type="success"
              size="mini"
              icon="el-icon-edit"
              @click="openEditDialog(row)"
              :disabled="!row.teacherId"
            >
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="table-pagination"
        background
        layout="total, prev, pager, next, jumper, sizes"
        :current-page="queryParams.pageNo"
        :page-size="queryParams.pageSize"
        :page-sizes="[5, 10, 20]"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>

    <el-dialog :visible.sync="dialogVisible" title="分配授课教师">
      <div style="margin-bottom: 10px">
        <div style="margin-bottom: 10px">班级：{{ currentRow.className }}</div>
        <div style="margin-bottom: 10px">课程：{{ currentRow.courseName }}</div>
      </div>
      <span style="margin-right: 20px">请选择教师:</span>
      <el-select
        v-model="selectedTeacherId"
        placeholder="请选择教师"
        filterable
        clearable
        :disabled="currentRow.teacherId != null"
      >
        <el-option
          v-for="teacher in teacherList"
          :key="teacher.id"
          :label="teacher.username"
          :value="teacher.id"
        />
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="assignTeacher"
          :disabled="currentRow.teacherId != null"
          >确定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog :visible.sync="editDialogVisible" title="修改授课教师">
      <div style="margin-bottom: 10px">
        <div>班级：{{ editRow.className }}</div>
        <div>课程：{{ editRow.courseName }}</div>
        <div>当前教师：{{ editRow.teacherName || "无" }}</div>
      </div>
      <span style="margin-right: 20px">请选择教师:</span>
      <el-select
        v-model="editTeacherId"
        placeholder="请选择教师"
        filterable
        clearable
        :disabled="hasScore"
      >
        <el-option
          v-for="teacher in editTeacherList"
          :key="teacher.id"
          :label="teacher.username"
          :value="teacher.id"
        />
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="editTeacherConfirm"
          :disabled="hasScore"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getMajorByDeptId } from "@/api/major";
import { getAllSemester } from "@/api/semester";
import {
  getAllCourseDetail,
  assignTeacherApi,
  updateTeacher,
} from "@/api/course";
import { getTeacherById } from "@/api/user";
import { mapState } from "vuex";
import { getScoreByCourseId } from "@/api/score";
export default {
  data() {
    return {
      queryParams: {
        deptId: "",
        majorId: "",
        semesterId: "",
        assignStatus: null,
        className: "",
        pageNo: 1,
        pageSize: 10,
      },
      total: 0, // 总条数
      majorList: [],
      semesterList: [],
      tableData: [],
      teacherList: [],
      dialogVisible: false,
      currentRow: {},
      selectedTeacherId: null,

      editDialogVisible: false,
      editTeacherId: null,
      editTeacherList: [],
      editRow: {},

      // 分配状态
      assignStatusList: [
        {
          id: 0,
          status: "未分配",
        },
        {
          id: 1,
          status: "已分配",
        },
      ],

      hasScore: false,
    };
  },
  computed: {
    ...mapState("dept", ["departments"]),
  },

  methods: {
    // 获取所有系的id和name
    getAllDeptInfo() {
      this.$store.dispatch("dept/getAllDept");
    },
    // 处理页码变化
    handleCurrentChange(currentPage) {
      this.queryParams.pageNo = currentPage;
      this.getTableData(this.queryParams);
    },

    // 处理每页显示条数变化
    handleSizeChange(size) {
      this.queryParams.pageSize = size;
      this.queryParams.pageNo = 1; // 重置为第一页
      this.getTableData(this.queryParams);
    },

    // 打开修改授课老师对话框
    async openEditDialog(row) {
      if (!row.teacherId) {
        this.$message.warning("该课程未分配授课老师，不能修改授课老师");
        return;
      }
      this.editRow = row;
      this.editTeacherId = row.teacherId;
      this.editDialogVisible = true;

      const payload = {
        id: this.editRow.id,
        courseId: this.editRow.courseId,
        teacherId: this.editTeacherId,
        semesterId: this.editRow.semesterId,
      };

      // 查询是否有成绩
      let res = await getScoreByCourseId(payload);
      console.log("查询成绩的结果为:", res);

      // 标记是否有成绩，用于禁用下拉框
      this.hasScore = res.code != 200;

      if (this.hasScore) {
        this.$message.error("该课程已存在成绩，不能修改授课老师");
        // 不需要return，让用户可以看到当前教师信息，但不能修改
      }

      // 查询教师列表
      try {
        let res = await getTeacherById(row.deptId);
        if (res.code == 200) {
          this.editTeacherList = res.data || [];

          // 确保当前教师在列表中
          if (row.teacherId && row.teacherName) {
            const currentTeacherExists = this.editTeacherList.some(
              (teacher) => teacher.id === row.teacherId
            );
            if (!currentTeacherExists) {
              // 如果当前教师不在列表中，添加到列表
              this.editTeacherList.push({
                id: row.teacherId,
                username: row.teacherName,
              });
            }
          }
        }
      } catch (error) {
        console.error("获取教师列表失败:", error);
      }
    },

    // 修改授课老师
    async editTeacherConfirm() {
      if (this.hasScore) {
        this.$message.error("该课程已存在成绩，不能修改授课老师");
        return;
      }

      if (!this.editTeacherId) {
        this.$message.warning("请先选择教师");
        return;
      }
      // 调用新的后端接口 editTeacherApi
      const payload = {
        id: this.editRow.id,
        courseId: this.editRow.courseId,
        teacherId: this.editTeacherId,
        semesterId: this.editRow.semesterId,
      };
      try {
        const res = await updateTeacher(payload);
        if (res.code === 200) {
          this.$message.success(res.data);
          this.editDialogVisible = false;
          this.getTableData(this.queryParams); // 刷新列表
        } else {
          this.$message.error(res.msg);
        }
      } catch (error) {}
    },

    //分配状态改变
    assignStatusChange() {
      this.getTableData(this.queryParams);
    },

    formatTeacherName(row) {
      return row.teacherName != null ? row.teacherName : "无";
    },
    // 获取学期信息
    async getSemester() {
      let res = await getAllSemester();
      this.semesterList = res.data;
    },

    //分页获取信息
    async getTableData(params) {
      const queryParams = {
        ...params,
        deptId: params.deptId !== "" ? Number(params.deptId) : null,
        majorId: params.majorId !== "" ? Number(params.majorId) : null,
        semesterId: params.semesterId !== "" ? Number(params.semesterId) : null,
      };
      console.log("分页的参数", queryParams);
      try {
        let res = await getAllCourseDetail(queryParams);
        console.log("查询的结果为:", res);
        this.tableData = res.data.records || [];
        this.total = res.data.total;
      } catch (e) {}
    },

    // 当院系发生改变
    async departmentChange(deptId) {
      // 先清空
      this.queryParams.majorId = "";
      this.queryParams.gradeId = "";
      this.majorList = [];
      this.queryParams.pageNo = 1;

      this.getTableData(this.queryParams);

      console.log("部门改变id", deptId);
      // 调用接口获取专业信息
      if (!deptId) {
        return;
      }
      try {
        let res = await getMajorByDeptId(deptId);
        this.majorList = res.data || [];
      } catch (error) {
        console.log(error);
      }
    },

    // 专业发生改变
    async majorChange() {
      // 清空
      this.queryParams.gradeId = "";
      this.queryParams.pageNo = 1;
      this.getTableData(this.queryParams);
    },

    gradeSemester() {
      this.getTableData(this.queryParams);
    },

    //点击查询按钮
    queryClass() {
      this.getTableData(this.queryParams);
    },

    // 打开dialog
    async openAssignDialog(row) {
      this.currentRow = row;
      this.selectedTeacherId = row.teacherId;
      this.dialogVisible = true;
      // 根据deptId查询对应学院的老师
      let { deptId } = row;
      try {
        let res = await getTeacherById(deptId);
        if (res.code == 200) {
          this.teacherList = res.data || [];
        }
      } catch (error) {}
    },

    async assignTeacher() {
      const payload = {
        id: this.currentRow.id,
        courseId: this.currentRow.courseId,
        teacherId: this.selectedTeacherId,
      };

      console.log("分配的参数:", payload);
      try {
        const res = await assignTeacherApi(payload);
        if (res.code === 200) {
          this.$message.success(res.data);
          this.dialogVisible = false;
          this.getTableData(this.queryParams); // 刷新列表
        } else {
          this.$message.error(res.msg);
        }
      } catch (error) {}
    },
  },
  mounted() {
    // this.getTableData();
    this.getTableData(this.queryParams);
    this.getSemester();
    this.getAllDeptInfo();
  },
};
</script>

<style lang="scss" scoped>
#container {
  margin: 20px;

  .header {
    display: flex;
    flex-wrap: wrap;
    gap: 16px; // 控制各项间距
    align-items: center;
  }

  .form-item {
    display: flex;
    align-items: center;
    min-width: 200px;
    flex: 1; // 让所有form-item平均分配空间
    white-space: nowrap;

    span {
      margin-right: 8px;
      font-weight: 500;
      white-space: nowrap;
    }

    .el-input,
    .el-select {
      flex: 1;
      min-width: 120px;
    }
  }

  .content {
    margin-top: 30px;
    .el-pagination {
      margin-top: 30px;
      display: flex;
      justify-content: center; // ✅ 水平居中
    }
  }
}
</style>
